package memberrank

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateMemberRankLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateMemberRankLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateMemberRankLogic {
	return &BackendUpdateMemberRankLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: memberrank
func (l *BackendUpdateMemberRankLogic) BackendUpdateMemberRank(in *setting.MemberRankInfo) (*setting.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	rank, err := l.svcCtx.MemberRank.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Sort != nil {
		rank.Sort = uint16(*in.Sort)
	}
	if in.Name != nil {
		rank.Name = strings.TrimSpace(*in.Name)

		if len(rank.Name) == 0 {
			logx.Errorw("update member rank failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("setting.memberRankNameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankColumns.Name] = map[string][]any{
			"equalTo": []any{rank.Name},
		}
		list, _, err := l.svcCtx.MemberRank.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}
	}
	if in.Code != nil {
		rank.Code = strings.TrimSpace(*in.Code)

		if len(rank.Code) == 0 {
			logx.Errorw("update member rank failed, its code is required")
			return nil, errorx.NewInvalidArgumentError("setting.memberRankCodeRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankColumns.Code] = map[string][]any{
			"equalTo": []any{rank.Code},
		}
		list, _, err := l.svcCtx.MemberRank.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("setting.memberRankAlreadyExists")
		}
	}
	if in.Description != nil {
		rank.Description = strings.TrimSpace(*in.Description)
	}
	if in.Remark != nil {
		rank.Remark = strings.TrimSpace(*in.Remark)
	}
	if in.PicId != nil {
		rank.PicID = *in.PicId
	}
	if in.PicUrl != nil {
		rank.PicURL = strings.TrimSpace(*in.PicUrl)
	}
	if in.PointThreshold != nil {
		rank.PointThreshold = uint(*in.PointThreshold)
	}
	if in.IsDefault != nil {
		rank.IsDefault = uint8(*in.IsDefault)
	}
	if in.Status != nil {
		rank.Status = uint8(*in.Status)
	}
	rank.UpdatedAt = time.Now()

	sysMemberRankRel := &model.SysMemberRankRel{}
	if len(in.Restrictions) > 0 {
		relFilterMap := make(map[string]map[string][]any)
		relFilterMap[model.SysMemberRankRestrictionColumns.RankID] = map[string][]any{
			"equalTo": []any{id},
		}
		rel, _, err := l.svcCtx.MemberRank.GetRestrictionList(l.ctx, model.M{}, -1, relFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		var rids []uint64
		oridMap := make(map[uint64]struct{})
		if len(rel) > 0 { // 原有的 Restrictions（决定现有的是增还是改）
			for _, v := range rel {
				rids = append(rids, v.RestrictionID)
				oridMap[v.RestrictionID] = struct{}{}
			}
		}

		// 现有的 Restrictions（决定原有的是删还是留）
		nridMap := make(map[uint64]struct{})
		for _, v := range in.Restrictions {
			if v.TaskId == nil || v.Threshold == nil {
				continue
			}

			var restriction model.SysMemberRankRestriction
			restriction.RankID = id
			restriction.TaskID = *v.TaskId
			restriction.Threshhold = uint(*v.Threshold)
			if v.Sort != nil {
				restriction.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				restriction.Status = uint8(*v.Status)
			} else {
				restriction.Status = uint8(globalkey.StatusEnabled)
			}

			if v.Id != nil && *v.Id > 0 {
				if _, ok := oridMap[*v.Id]; ok { // 有值且是有效值
					nridMap[*v.Id] = struct{}{}
					restriction.RestrictionID = *v.Id
				}
			}

			sysMemberRankRel.Restrictions = append(sysMemberRankRel.Restrictions, &restriction)
		}

		for _, rid := range rids {
			if _, ok := nridMap[rid]; !ok { // 当前不存在的值
				sysMemberRankRel.DelRestrictionIds = append(sysMemberRankRel.DelRestrictionIds, rid)
			}
		}
	}
	if len(in.Rules) > 0 {
		relFilterMap := make(map[string]map[string][]any)
		relFilterMap[model.SysMemberRankRuleColumns.RankID] = map[string][]any{
			"equalTo": []any{id},
		}
		rel, _, err := l.svcCtx.MemberRank.GetRuleList(l.ctx, model.M{}, -1, relFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		var rids []uint64
		oridMap := make(map[uint64]struct{})
		if len(rel) > 0 { // 原有的 Rules（决定现有的是增还是改）
			for _, v := range rel {
				rids = append(rids, v.RuleID)
				oridMap[v.RuleID] = struct{}{}
			}
		}

		// 现有的 Rules（决定原有的是删还是留）
		nridMap := make(map[uint64]struct{})
		for _, v := range in.Rules {
			var rule model.SysMemberRankRule
			rule.RankID = id
			if v.RuleType != nil {
				rule.RuleType = uint8(*v.RuleType)
				switch rule.RuleType {
				case enum.MemberRankRuleTypeDiscount, enum.MemberRankRuleTypeGems:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)

						if v.Value != nil {
							switch rule.Mode {
							case enum.MemberRankRuleModeAmount:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.MemberRankRuleModeDiscount:
								if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 && i <= 100 {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							case enum.MemberRankRuleModeFixed:
								if i, err := moneyx.ParseAmount(*v.Value); err == nil {
									rule.Value = uint64(i)
								} else {
									return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
								}
							default:
								return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
							}
						}
					}
				case enum.MemberRankRuleTypeFreeShipping:
					if v.Mode != nil {
						rule.Mode = uint8(*v.Mode)
					}

					if v.Regions != nil {
						rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
					}
				case enum.MemberRankRuleTypeExtraPoint:
					if v.Value != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.MemberRankRuleTypeCoupon:
					if v.Value != nil && v.PeriodType != nil && v.Quota != nil {
						if i, err := strconv.ParseInt(*v.Value, 10, 32); err == nil && i > 0 {
							rule.Value = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
						rule.PeriodType = uint8(*v.PeriodType)
						rule.Quota = uint8(*v.Quota)
					}
				}
			}
			if v.Sort != nil {
				rule.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				rule.Status = uint8(*v.Status)
			} else {
				rule.Status = uint8(globalkey.StatusEnabled)
			}

			if v.Id != nil && *v.Id > 0 {
				if _, ok := oridMap[*v.Id]; ok { // 有值且是有效值
					nridMap[*v.Id] = struct{}{}
					rule.RuleID = *v.Id
				}
			}

			sysMemberRankRel.Rules = append(sysMemberRankRel.Rules, &rule)
		}

		for _, rid := range rids {
			if _, ok := nridMap[rid]; !ok { // 当前不存在的值
				sysMemberRankRel.DelRuleIds = append(sysMemberRankRel.DelRuleIds, rid)
			}
		}
	}
	err = l.svcCtx.MemberRank.Update(l.ctx, nil, rank, sysMemberRankRel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
